import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
import router from './router'
import store from './store'


Vue.use(ElementUI);


Vue.config.productionTip = false


// 封装 set localStorage函数
Vue.prototype.setLocalValue = function (name, value) {
  if (window.localStorage) {
    localStorage.setItem(name, value);
  } else {
    alert('This browser does NOT support localStorage');
  }
};

// 封装 get localStorage函数
Vue.prototype.getLocalValue = function (name) {
  const value = localStorage.getItem(name);
  if (value) {
    return value;
  } else {
    return '';
  }
};
router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  setTimeout(() => {
    if (to.meta.title) {
      document.title = to.meta.title
    }

    if (to.meta.requireAuth) {
      if (store.state.token !== '') {
        next();
      } else {
        next({
          name: 'Login',
        })
      }
    } else {
      next()
    }
  })
})

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App),
  template: '<App/>',
  components: {App},
  created() {
    if (this.getLocalValue("token") === null) {
      this.setLocalValue("token", "");
    }
    if (this.getLocalValue("user") === null) {
      this.setLocalValue("user", "");
    }
    if (this.getLocalValue("routerName") === null) {
      this.setLocalValue("routerName", "ProjectList");
    }
    // this.$store.commit("isLogin", this.getLocalValue("token"));
    // this.$store.commit("setUser", this.getLocalValue("user"));
    this.$store.commit("setRouterName", this.getLocalValue("routerName"));
  }
})
